<template>
	<view class="order_pay" :style="viewColor">
		<view class="order_count">
			<view class="pay_wrap">
				<view class="pay_price">
					付款给商家
					<!-- <priceFormat :price="payPrice" weight intSize="52" floatSize="40" labelSize="40"></priceFormat> -->
				</view>
				<view class="pay_shops">
					<view class="pay_title">{{merchantInfo.mer_name}}</view>
					<image src="../../../static/images/logos.png" mode=""></image>
				</view>
			</view>

			<view class="pay_input">
				<view class="pay_wrap">
					<view class="pay_input_title">金额</view>
					<div class="item pay_flex">
						<span>￥</span>
						<input type="number" placeholder="输入金额" placeholder-class="placeholder" v-model="money"
							required />
					</div>
				</view>
			</view>
		</view>
		<view class="payment boder-24 bg-f">
			<radio-group @change="changeType">
				<label class="item acea-row row-between-wrapper" v-for="(item, index) in payMode"
					v-if="item.payStatus == 1" :key="index">
					<view class="left acea-row row-between-wrapper">
						<view class="icon acea-row row-center row-middle" :class="'icons-' + item.icon">
							<view class="iconfont" :class="item.icon"></view>
						</view>
						<view class="text">
							<view class="name">{{ item.name }}</view>
							<view class="info">{{ item.title }} {{ item.value === 'balance' ? item.number : '' }}</view>
						</view>
					</view>
					<radio :value="item.value" :checked="pay_type == item.value" />
				</label>
			</radio-group>
			<view class="btn">
				<view class="button acea-row row-center-wrapper" @click="goPay()">确认支付</view>
				<!-- <view class="wait-pay" @click="waitPay">暂不支付</view> -->
			</view>
		</view>
	</view>
</template>

<script>
	// +----------------------------------------------------------------------
	// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
	// +----------------------------------------------------------------------
	// | Copyright (c) 2016~2024 https://www.crmeb.com All rights reserved.
	// +----------------------------------------------------------------------
	// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
	// +----------------------------------------------------------------------
	// | Author: CRMEB Team <admin@crmeb.com>
	// +----------------------------------------------------------------------
	let app = getApp();
	import {
		mapGetters
	} from 'vuex';
	import {
		configMap
	} from '@/utils';
	//import countDown from '@/components/countDown';
	import {
		toLogin
	} from '@/libs/login.js';
	import {
		getUserInfo,
		getOpenidxcx
	} from '@/api/user.js';
	import {
		orderPay,
		integralOrderPay,
		getCashierOrder,
		getOrderPayTypeList,
		maPai,
		orderMapai_order,
		orderMapai_pay
	} from '@/api/order.js';
	export default {
		components: {
		//	countDown
		},
		data() {
			return {
				invalidTime: 0,
				mapai_id: '',
				order_id: '',
				payPrice: '',
				order_type: '',
				//pay_type: '',
				number: 0,
				payMode: this.orderPayList,
				merchantInfo: {},
				bianmami: '',
				money: '',
				pay_type: '',
				open_id: ''
			};
		},
		computed: {
			...mapGetters(['isLogin', 'viewColor', 'orderPayList']),
			...configMap(['hide_mer_status']),
		},
		watch: {
			// orderPayList:{
			// 	handler(nVal,oVal){
			// 		if(nVal && this.order_id){
			// 			this.payMode= nVal;
			// 			this.getOrderConfig()
			// 		}
			// 	},
			// 	immediate: true,
			// 	deep:true
			// }
		},
		onLoad(options) {
			if (options.bianmami) {
				this.mapai_id = options.bianmami
				uni.setStorageSync('mapai_id', options.bianmami)
			}
			/* if(uni.getStorageSync('wxcode')){
				let code = uni.getStorageSync('wxcode')				
				this.getopenId(code)
			} */
			uni.setStorageSync('backPayurl', '/pages/users/pay_page/index?bianmami=' + this.mapai_id)
			this.getPayInfo()
			// var ua = window.navigator.userAgent.toLowerCase();
			// if (ua.match(/MicroMessenger/i) == 'micromessenger') {
			// 	console.log("这是微信浏览器");
			// 	this.pay_type = 2
			// } else {
			// 	console.log("这是普通浏览器");
			// 	this.pay_type = 1
			// }
			// let isWX = this.isWechat()
			// if (isWX) {
			// 	this.pay_type = 2
			// 	this.getWXCode()
			// } else {
			// 	this.pay_type = 1
			// }



		},
		onReady(){
			let that = this
			// #ifdef MP
			uni.login({
			  success (res) {
			    if (res.code) {
					 console.log('登录失败！' +res.code)
			    // that.codeVal = res.code
			    } else {
			      console.log('登录失败！' + res.errMsg)
			    }
			  }
			})
			// #endif
		},
		methods: {
			// 判断是否为微信环境
			isWechat() {
				var ua = navigator.userAgent.toLowerCase()
				var isWXWork = ua.match(/wxwork/i) == 'wxwork'
				var isWeixin = !isWXWork && ua.match(/MicroMessenger/i) == 'micromessenger'
				return isWeixin
			},
			getWXCode() {
				let appid = 'wx43a8af4d81c817ba' //公众号的唯一标识
				//let  secret='=5da375cb60b3de893c93075502b7cf19'
				let code = this.getUrlCode().code; //是否存在code
				//alert(code)
				const url = window.location.href;
				//let url = 'https://m.lnzld.com/pages/users/pay_page/index?bianmami=fa2a9faa8ea5067533e38ac0960c2033' //授权后重定向的回调链接地址
				if (code == null || code === "") {
					window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + appid +
						'&secret=' + secret +
						'&redirect_uri=' + encodeURIComponent(url) +
						'&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect'
				} else {
					alert(code)
					//this.code = code;
					this.getopenId(code)

				}

			},
			getopenId(code) {
				var that = this
				//alert('个人信息，获取openid')
				let data = {
					type: 1,
					code: code
				}
				getOpenidxcx(data).then(res => {
					console.log(res.data, '个人信息，获取openid')
					that.open_id = res.data.openid
				});
			},
			// 截取url中的code方法
			getUrlCode() {
				// 截取url中的code方法
				var url = location.search;
				var theRequest = new Object();
				if (url.indexOf("?") != -1) {
					var str = url.substr(1);
					var strs = str.split("&");
					for (var i = 0; i < strs.length; i++) {
						theRequest[strs[i].split("=")[0]] = strs[i].split("=")[1];
					}
				}
				return theRequest;
			},
			/*
			 * 获取用户信息
			 */
			getUserInfo: function() {
				var that = this
				getUserInfo().then(res => {
					console.log(res.data, '个人信息')
					that.open_id = res.data.openid
				});
			},
			getPayInfo() {
				maPai(this.mapai_id).then(res => {
					//console.log(res)
					if (res.status == 200) {
						this.merchantInfo = res.data
						this.bianmami = res.data.bianmami
						getUserInfo().then(ret => {
							console.log(ret.data, '个人信息')
							this.open_id = ret.data.openid
						})			
					} else if (res.status == 401) {
						uni.navigateTo({
							url: '/pages/users/login/index',
						});
					} else {
						uni.showToast({
							icon: 'none',
							title: res.status.message,
						})
					}
				}).catch(err => {
					console.log('weidegnlu', this.$wechat.isWeixin())
					console.log(err, '报错信息')
					//alert(err)
					toLogin()
					// if (this.$wechat.isWeixin()) {
					// 	uni.navigateTo({
					// 		url: '/pages/users/wechat_login/index?type=wechat',
					// 	});

					// } else {
					// 	return uni.navigateTo({
					// 		url: '/pages/users/login/index?type=zfb'
					// 	})
					// }


				});
			},
			close: function() {
				this.$emit('onChangeFun', {
					action: 'payClose'
				});
			},
			changeType: function(e) {
				this.pay_type = e.detail.value;
			},
			goPay() {
				if (this.money == '') {
					uni.showToast({
						icon: 'none',
						title: '请输入金额',
					})
					return false;
				}
				orderMapai_order({
					bianmami: this.bianmami,
					money: this.money,
					pay_type: this.pay_type
				}).then((res) => {
					if (res.status == 200) {
						// console.log(res)
						let datas = res.data
						if (datas.xianjin = 0) {
							uni.showToast({
								title: res.message,
								icon: 'none'
							})
						} else {
							this.goPayzf(res.data.order_sn)
						}

					} else {
						//console.log('授权登录')
						toLogin()
					}
					console.log(res)
				})
			},
			goPayzf(order_sn) {
				let that = this;
				if (that.open_id == '' && this.pay_type == 2) {
					uni.navigateTo({
						url: '/pages/users/wechat_login/index',
					})
					// uni.showToast({
					// 	icon: 'none',
					// 	title: 'open_id不能为空',
					// })
					return false;
				}
				orderMapai_pay({
					order_sn: order_sn,
					open_id: that.open_id
				}).then((res) => {
					if (res.status == 200) {
						if (this.pay_type == 1) {
							window.location.href = res.data.info
						} else {
							uni.showLoading({
								title: '支付中...',
								mask: true
							})
							const payParams = res.data.info
							if (typeof WeixinJSBridge === "undefined") {
								if (document.addEventListener) {
									document.addEventListener('WeixinJSBridgeReady', () => {
										this.executePayment(payParams)
									}, false)
								} else if (document.attachEvent) {
									document.attachEvent('WeixinJSBridgeReady', () => {
										this.executePayment(payParams)
									})
									document.attachEvent('onWeixinJSBridgeReady', () => {
										this.executePayment(payParams)
									})
								}
								uni.hideLoading()
								uni.showToast({
									title: '正在初始化支付环境...',
									icon: 'none'
								})
								return
							}

							const paymentResult = this.executePayment(payParams)
							console.log(paymentResult)
							// 4. 处理支付结果
							if (paymentResult) {
								uni.showToast({
									title: '您已支付',
									icon: 'none'
								})
								console.log('您已支付')
								// const res = await proxy.$api.get('/api/loanOrder/confirmLoanOrder', confirmParams.value)
								// if (res.code == '200') {
								// 	isShowInite(true)
								// }

							} else {
								uni.showToast({
									title: '您已取消支付',
									icon: 'none'
								})
							}
						}
					} else {
						console.log('授权登录')

						toLogin()
					}
					console.log(res)
				})
			},
			executePayment(info) {
				//const payParams = JSON.parse(info)
				const payParams = info
				// console.log('传参结果123')
				// console.log(payParams)
				// console.log('传参结果456')
				return new Promise((resolve, reject) => {
					WeixinJSBridge.invoke(
						'getBrandWCPayRequest', {
							appId: payParams.appId,
							timeStamp: payParams.timeStamp,
							nonceStr: payParams.nonceStr,
							package: payParams.package,
							signType: payParams.signType,
							paySign: payParams.paySign
						},
						(res) => {
							if (res.err_msg === 'get_brand_wcpay_request:ok') {
								resolve(true) // 支付成功
							} else if (res.err_msg === 'get_brand_wcpay_request:cancel') {
								resolve(false) // 用户取消
							} else {
								reject(new Error(res.err_msg || '支付失败'))
							}
						}
					)
				})
			},


		}
	};
</script>

<style scoped lang="scss">
	.order_pay {
		padding: 88rpx 0;
	}

	.payment {
		margin-top: 80rpx;
	}

	.pay_price {
		font-weight: bold;
		padding-bottom: 20rpx;
	}

	.pay_wrap {
		width: 92%;
		margin: 0 4%;
	}

	.pay_flex {
		display: flex;
		align-items: center;
		justify-content: space-around;
	}

	.pay_shops {
		display: flex;
		justify-content: space-between;
		align-items: center;

		image {
			width: 120rpx;
			height: 120rpx;
			border-radius: 100%;
		}

	}

	.pay_input {
		background-color: #fff;
		border-radius: 40rpx 40rpx 0 0;
		padding: 20rpx 0 200rpx 0;
		margin-top: 40rpx;

		.pay_input_title {
			font-size: 24rpx;
			color: #282828;
		}

		.item {
			margin-top: 50rpx;
			padding-bottom: 40rpx;
			border-bottom: 2rpx solid #aaa;

			span {
				font-size: 50rpx;
				color: #030303;
				width: 20%;
			}

			input {
				color: #000;
				width: 75%;
				font-size: 40rpx;
			}
		}
	}

	.pay_time {
		margin-top: 28rpx;
	}

	.payment .item {
		height: 130rpx;
		padding: 0 30rpx;
	}

	.payment .item .left {
		width: 580rpx;
	}

	.payment .item .left .text {
		width: 500rpx;
	}

	.payment .item .left .text .name {
		font-size: 28rpx;
		color: #282828;
	}

	.payment .item .left .text .info {
		font-size: 22rpx;
		color: #999;
	}

	.payment .item .left .text .info .money {
		color: #ff9900;
	}

	/deep/radio .uni-radio-input.uni-radio-input-checked,
	/deep/radio .wx-radio-input.wx-radio-input-checked {
		border: 1px solid var(--view-theme) !important;
		background-color: var(--view-theme) !important;
	}

	.btn {
		position: fixed;
		left: 30rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		bottom: 30rpx;
		bottom: calc(30rpx + constant(safe-area-inset-bottom)); ///兼容 IOS<11.2/
		bottom: calc(30rpx + env(safe-area-inset-bottom)); ///兼容 IOS>11.2/
	}

	.wait-pay {
		color: #aaa;
		font-size: 24rpx;
		padding-top: 20rpx;
	}

	.button {
		width: 690rpx;
		height: 90rpx;
		border-radius: 45rpx;
		color: #ffffff;
		background-color: var(--view-theme);
	}
</style>